package com.zh.eventdispatch.activity;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.view.ViewGroup;
import android.view.ViewParent;

/**
 * @author wally
 * @date 2021/06/19
 */
public class ActivityEventHelper {
    private final ActivityEventDispatcher mChildEventDispatcher = new ActivityEventDispatcher();
    private final Context mContext;
    private final ActivityEventView mEventView;

    public ActivityEventHelper(Context context, ActivityEventView eventView) {
        this.mContext = context;
        this.mEventView = eventView;
    }

    public void onAttachedToWindow() {
        ActivityEventDispatcher dispatcher = findParentEventDispatcher(mEventView.getParent());
        if (dispatcher != null) {
            dispatcher.addObserver(mEventView);
        }
    }

    public void onDetachedFromWindow() {
        ActivityEventDispatcher dispatcher = findParentEventDispatcher(mEventView.getParent());
        if (dispatcher != null) {
            dispatcher.removeObserver(mEventView);
        }
    }

    /**
     * 寻找事件分发器
     */
    private ActivityEventDispatcher findParentEventDispatcher(ViewParent parent) {
        //父View实现了ActivityEventView接口
        if (parent instanceof ActivityEventView) {
            ActivityEventView eventView = (ActivityEventView) parent;
            return eventView.getEventDispatcher();
        } else if (parent instanceof ViewGroup) {
            //父View没有实现接口，则尝试找它的父View，看有没有实现接口
            ViewGroup group = (ViewGroup) parent;
            return findParentEventDispatcher(group.getParent());
        }
        //都找不到，则从Activity上寻找分发器，它是最根层的
        Activity activity = getActivity(mContext);
        if (activity instanceof ActivityEventOwner) {
            ActivityEventOwner owner = (ActivityEventOwner) activity;
            return owner.getEventDispatcher();
        }
        //Activity也找不到，证明Activity没有实现ActivityEventOwner接口，所以也不可能有事件分发出来了
        return null;
    }

    public ActivityEventDispatcher getEventDispatcher() {
        return mChildEventDispatcher;
    }

    private Activity getActivity(Context context) {
        while (context instanceof ContextWrapper) {
            if (context instanceof Activity) {
                return (Activity) context;
            }
            context = ((ContextWrapper) context).getBaseContext();
        }
        return null;
    }
}